<script setup>
import { userService_login, userService_register } from '@/apis/user.js'
import { validatePassword, validateUserName } from '@/utils/validator'
import { Back, Lock, Right, User } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserInfo } from '@/stores/index.js'

/**
 * 数据区
 */
// 1. 获取路由实例
const router = useRouter()

/**
 * 2. 验证规则
 */
let isLogin = ref(true) // 是否登录
const loginForm = reactive({
  username: '',
  password: '',
  repassword: ''
})
// 定义验证规则
const myRule = reactive({
  // 用户名验证规则
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    // 密码长度必须是6-15的非空字符
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
  ],
  repassword: [
    {
      // 校验的规则，获取到的值
      validator: (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('密码不能为空'))
        }
        if (loginForm.password !== value) {
          callback(new Error('两次密码不一致'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ]
})

/**
 * pinia-公共数据区
 */
const userStore = useUserInfo()

const { setToken } = userStore
/**
 * 3. 方法区
 */

//  1. 登录 【组合式API的写法】
const login = async () => {
  // 用户输入控制
  validateUserName(loginForm.username)
  validatePassword(loginForm.password)
  // 是否考虑一下组件封装?
  const res = await userService_login(loginForm.username, loginForm.password)
  ElMessage({
    showClose: true,
    message: res.message,
    type: 'success'
  })

  // 登录成功，存token
  setToken(res.token)

  // 跳转到首页
  console.log(router)
  router.push('/')
}

// 2. 注册
const register = async () => {
  // 用户输入控制
  validateUserName(loginForm.username)
  validatePassword(loginForm.password)
  if (loginForm.repassword === '') {
    ElMessage({
      showClose: true,
      message: '请输入确认密码',
      type: 'error'
    })
    return
  }
  if (loginForm.repassword !== loginForm.password) {
    ElMessage({
      showClose: true,
      message: '两次密码不一致',
      type: 'error'
    })
    return
  }
  // 是否考虑一下组件封装?
  const res = await userService_register(
    loginForm.username,
    loginForm.password,
    loginForm.repassword
  )
  ElMessage({
    showClose: true,
    message: res.message,
    type: 'success'
  })
  isLogin.value = true
}
</script>

<template>
  <el-row class="login-container">
    <el-col :span="12">
      <div class="bg_box"></div>
    </el-col>

    <el-col :span="12" class="login_form flex" v-if="isLogin">
      <el-col :span="12" :offset="6">
        <!-- 注意：在表单元素中也要绑定，绑定表单元素 -->
        <el-form :rules="myRule" status-icon :model="loginForm">
          <el-form-item>
            <h1 class="login_title">登录</h1>
          </el-form-item>

          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.username"
              placeholder="请输入用户名"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
            />
          </el-form-item>

          <el-form-item>
            <div class="flex remeber">
              <label>
                <input type="checkbox" name="" id="rember" />记住我
              </label>
              <el-link type="primary" :underline="false">忘记密码?</el-link>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              width="100%"
              class="login_btn"
              @click="login()"
              >登录</el-button
            >
          </el-form-item>

          <!-- 注册 -->
          <el-form-item>
            <el-link :underline="false" @click="isLogin = false">
              <span class="register">注册</span>
            </el-link>
            <el-icon>
              <Right />
            </el-icon>
          </el-form-item>

          <!-- 底部提示 -->
          <footer>
            <p class="tips">
              仅用于个人项目练习使用，为保障您的个人信息安全，请勿向平台录入任何个人敏感信息（如手机号、身份证号等）！
            </p>
          </footer>
        </el-form>
      </el-col>
    </el-col>

    <el-col :span="12" class="login_form flex" v-else>
      <el-col :span="12" :offset="6">
        <el-form :rules="myRule" :model="loginForm">
          <el-form-item>
            <h1 class="login_title">注册</h1>
          </el-form-item>

          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.username"
              placeholder="请输入用户名"
            />
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
            />
          </el-form-item>

          <el-form-item prop="repassword">
            <el-input
              :prefix-icon="Lock"
              v-model="loginForm.repassword"
              type="password"
              placeholder="请确认密码"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              width="100%"
              class="login_btn"
              @click="register"
              >注册</el-button
            >
          </el-form-item>

          <!-- 注册 -->
          <el-form-item>
            <el-icon>
              <Back />
            </el-icon>
            <el-link :underline="false" @click="isLogin = true">
              <span class="register">返回</span>
            </el-link>
          </el-form-item>
        </el-form>
      </el-col>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
}
.flex {
  display: flex;
}

:deep .el-input__wrapper {
  height: 2.5067rem;
}

// 左侧
.bg_box {
  // 高度占满整个视口
  height: 100%;
  background: url('@/assets/logo.png') no-repeat 60% center/240px auto,
    url('@/assets/login_bg.jpg') no-repeat center/cover;
  border-radius: 0rem 1.6rem 1.6rem 0rem;
}

// 表单
.login_form {
  // 纵向排列
  align-items: center;

  .login_title {
    line-height: 2.5333rem;
  }

  .remeber {
    width: 100%;
    justify-content: space-between;
  }

  .login_btn {
    height: 2.533rem;
    width: 100%;
  }

  input#rember {
    vertical-align: middle;
  }

  footer {
    .tips {
      line-height: 2.4666rem;
    }
  }
}

// 每一个表单项
.el-form-item {
  margin-bottom: 1.4rem;
}
</style>
